<?php
/*
Plugin Name: JayBo Category Ordering
Plugin URI: http://www.jaybowalkin.com/categories/plugins
Description: Drag and drop your categories to order them correctly
ategories
Author: Bryan Clark
Version: 0.1
Author URI: http://www.jaybowalkin.com/
*/ 

/* Function Prefix: jaybo_category_ordering_ */

//require_once('../../wp-config.php');


function jaybo_category_ordering_init() {
	jaybo_category_ordering_check();
}
add_action('init', 'jaybo_category_ordering_init'); 

function jaybo_category_ordering_add_page() {
        if ( function_exists('add_management_page') )
                add_management_page('Category Ordering', 'Category Ordering', 'manage_categories', 'order-categories', jaybo_category_ordering_page);
}
add_action('admin_menu', 'jaybo_category_ordering_add_page');


function jaybo_category_ordering_libs() {
	if ( $_GET['page'] == "order-categories" ) {
		wp_enqueue_script( 'scriptaculous-effects' );
		wp_enqueue_script( 'scriptaculous-dragdrop' );
		wp_enqueue_script( 'wp-ajax' );
	} 
}
add_action('admin_menu', 'jaybo_category_ordering_libs');

function jaybo_category_ordering_save_order() {
	require_once('admin-functions.php');
	global $wpdb;

//	check_admin_referer('order-categories');

	parse_str(urldecode($_POST['term_order']), $term_order);

	$debug_order = "";
	if ( is_array( $term_order["categories"] ) ) {
		foreach ( $term_order["categories"] as $sort_index => $term_id ) {
			$debug_order .= $sort_index . " " . $term_id . ":";
			$wpdb->query( "UPDATE $wpdb->terms SET term_order = '$sort_index' WHERE term_id = '$term_id'" );
		}
	}

	$x = new WP_Ajax_Response( array(
		'what' => 'jaybo-category-ordering',
		'data' => 'Got It!&nbsp;&raquo;&nbsp;The Category Order was updated',
		'supplemental' => array('term_order' => implode($term_order["categories"], ", "))
	) );
	$x->send();

}
add_action('wp_ajax_jaybo_category_ordering_save_order', 'jaybo_category_ordering_save_order' );


function jaybo_category_ordering_page() {
	global $wpdb;

if ( isset( $_GET['ccat'] ) ) {
	$categories = $wpdb->get_results("SELECT * FROM $wpdb->terms JOIN $wpdb->term_taxonomy ON $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id WHERE ( count > 0 ) and parent = " . $_GET['ccat'] . " ORDER BY term_order ASC");

} else {
	$categories = $wpdb->get_results("SELECT * FROM $wpdb->terms JOIN  $wpdb->term_taxonomy ON $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id WHERE ( count > 0 ) and parent = 0 ORDER BY term_order ASC");
}
?>
	<style>
	#categories {
		list-style: none;
		width: 300px;
	}
	#categories li {
		cursor: move;
		border: 1px solid #888;
		padding: 0.5em;
	}
	</style>
	<script type="text/javascript">
	    //<![CDATA[
		function serializeAll() {
			document.getElementById("ser").value = Sortable.serialize('categories');
		}
		function initWidgets() {
		<?php
			foreach ( $categories as $index => $category ) :
		?>
			new Draggable('term-<?php echo $category->term_id; ?>', {revert:false,handle:'controlhandle',starteffect:function(){},endeffect:function(){},change:function(o){dragChange(o);}});

		<?php 	endforeach; ?>
		}
		function dragChange(o) {
			el = o.element ? o.element : $(o);
			var p = Position.page(el);
			var right = p[0];
			var top = p[1];
			var left = $('shadow').offsetWidth - (el.offsetWidth + right);
			var bottom = $('shadow').offsetHeight - (el.offsetHeight + top);
			if ( right < 1 ) el.style.left = 0;
			if ( top < 1 ) el.style.top = 0;
			if ( left < 1 ) el.style.left = (left + right) + 'px';
			if ( bottom < 1 ) el.style.top = (top + bottom) + 'px';
		}
		function jaybo_category_ordering_ajax_order( )
		{

			var term_order = Sortable.serialize('categories');

			var ajaxSave = new WPAjax( false , 'jaybo_category_ordering_ajax_response' );
			if ( ajaxSave.notInitialized() )
				return true;

			ajaxSave.addOnComplete( function(transport) {
				var msg = transport.responseXML.getElementsByTagName("response_data")[0];
				Element.update(ajaxSave.myResponseElement, '<div class="updated fade"><p>' + msg.textContent + '</p></div>');
				setTimeout(function() {Element.update(ajaxSave.myResponseElement, '');}, 10 * 1000);
			} );

			ajaxSave.addArg( "action", "jaybo_category_ordering_save_order" );
		  	ajaxSave.addArg( "term_order", term_order );

			ajaxSave.request(ajaxSave.url);

			return true;
		} 
	    //]]>
	</script>

	<div class="wrap">
		<h2><?php _e( 'Category Ordering' ); ?></h2>

		<p><?php _e( 'You can drag and drop categories to order them.' ); ?></p>

		<?php wp_dropdown_categories("orderby=term_order&order=ASC&hierarchical=1&show_option_all=Top Level&name=parent-cat&selected=".$_GET['ccat']); ?>

		<script type="text/javascript">
		    //<![CDATA[
		    var dropdown = document.getElementById("parent-cat");
		    function onCatChange() {
		                if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
		                location.href = "<?php echo get_option('siteurl'); ?>/wp-admin/edit.php?page=order-categories&ccat="+dropdown.options[dropdown.selectedIndex].value;
		                }
		    }
		    dropdown.onchange = onCatChange;
		    //]]>
		</script>

		<ul id="categories">
<?php			foreach ( $categories as $category ) : ?>
				<li class="controlhandle" id="term-<?php echo $category->term_id; ?>"><?php echo $category->name; ?></li>
<?php			endforeach; ?>
		</ul>
	
                        <script type="text/javascript">
                        // <![CDATA[
                                Sortable.create("categories", {
                                        dropOnEmpty: true, containment: false, 
                                        handle: 'container', constraint: false, onUpdate: function(){ jaybo_category_ordering_ajax_order (); }, 
                                        format: /^term-(.*)$/
                                });
                        // ]]>
                        </script>


		<br class="clear" />

		<div id="jaybo_category_ordering_ajax_response"></div>
	</div>
	
	<div id="shadow"> </div>
<?php 
}

/**
 *  Helper functions for this plugin
 *
 **/

function jaybo_category_ordering_check() {
	global $wpdb;
	global $cat_order_exists;
	if ( ! $cat_order_exists ) {
		if ( $columns = $wpdb->get_col ("SHOW columns FROM $wpdb->terms") ) {
			if ( ! in_array( "term_order", $columns ) )
				$wpdb->query ("ALTER TABLE $wpdb->terms ADD COLUMN term_order int(11) NOT NULL DEFAULT '0'");
			$cat_order_exists = true;
			return  $cat_order_exists;
		} 
	}
	return $cat_order_exists;
}

function jaybo_category_ordering_get_category_args() {
	return "hide_empty=1&orderby=term_order&order=ASC&hierarchical=0";
}

